package cn.edu.tju.core.security.service;

import cn.edu.tju.core.model.Authority;
import cn.edu.tju.core.security.repository.AuthorityRepository;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.edu.tju.core.security.SecurityUtils;
import cn.edu.tju.core.model.User;
import cn.edu.tju.core.security.repository.UserRepository;
import cn.edu.tju.core.security.rest.dto.UserDto; // 确保引入 UserDto
import cn.edu.tju.elm.service.WalletService;

import java.util.List;
import java.util.Optional;
import java.util.HashSet;
import java.util.Set;

@Service
@Transactional
public class UserService {

   private final UserRepository userRepository;
   private final AuthorityRepository authorityRepository;
   private final PasswordEncoder passwordEncoder;
   private final WalletService walletService;

   public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder, 
                     AuthorityRepository authorityRepository, WalletService walletService) {
      this.userRepository = userRepository;
      this.passwordEncoder = passwordEncoder;
      this.authorityRepository = authorityRepository;
      this.walletService = walletService;
   }

   public User createUser(UserDto userDto) {
      if (userRepository.findOneByUsername(userDto.getUsername()).isPresent()) {
         throw new RuntimeException("用户名 '" + userDto.getUsername() + "' 已被注册");
     }
     User newUser = new User();
     newUser.setUsername(userDto.getUsername());
     newUser.setPassword(passwordEncoder.encode(userDto.getPassword()));
     newUser.setActivated(true);
     Set<Authority> authorities = new HashSet<>();
     authorityRepository.findById("USER").ifPresent(authorities::add);
     newUser.setAuthorities(authorities);
     // 保存用户
     User savedUser = userRepository.save(newUser);
     
     // 自动为用户创建钱包
     try {
         if (!walletService.existsByUserId(savedUser.getId())) {
             walletService.createWallet(savedUser.getId(), savedUser);
         }
     } catch (Exception e) {
         // 如果钱包创建失败，记录日志但不影响用户注册
         // 在实际生产环境中，应该记录日志
         System.err.println("用户注册时创建钱包失败: " + e.getMessage());
     }
     
     return savedUser;
  }

   @Transactional(readOnly = true)
   public Optional<User> getUserWithAuthorities() {
      return SecurityUtils.getCurrentUsername().flatMap(userRepository::findOneWithAuthoritiesByUsername);
   }

   public User addUser(User user) {
      User savedUser = userRepository.save(user);
      
      // 自动为用户创建钱包（如果不存在）
      try {
          if (!walletService.existsByUserId(savedUser.getId())) {
              walletService.createWallet(savedUser.getId(), savedUser);
          }
      } catch (Exception e) {
          // 如果钱包创建失败，记录日志但不影响用户创建
          System.err.println("创建用户时创建钱包失败: " + e.getMessage());
      }
      
      return savedUser;
   }

   public User updateUser(User user) {
      return userRepository.save(user);
   }

   public Boolean isEmptyUserTable() {
      List<User> userList = userRepository.findAll();
      return userList.isEmpty();
   }
}
